package demo.gateway.metric;

import io.micrometer.core.instrument.MeterRegistry;
import io.netty.channel.EventLoopGroup;
import io.netty.util.ThreadDeathWatcher;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.ThreadPoolExecutor;

public class NettyMetricsRecorder {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(NettyMetricsRecorder.class);

    private final MeterRegistry meterRegistry;

    public NettyMetricsRecorder(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    public void recordThreadPoolMetrics(EventLoopGroup eventLoopGroup) {
        // 线程池指标
//        Gauge.builder("netty.threadpool.size",
//                        eventLoopGroup,
//                        this::getThreadPoolSize)
//                .register(meterRegistry);

        // 队列大小
//        Gauge.builder("netty.threadpool.queue.size",
//                        eventLoopGroup,
//                        this::getQueueSize)
//                .register(meterRegistry);
    }


    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void reportNettyMetrics() {
        ThreadDeathWatcher threadDeathWatcher = null;
        EventLoopGroup eventLoopGroup = null; // 需要从Spring容器中获取

        if (eventLoopGroup instanceof ThreadPoolExecutor) {
            ThreadPoolExecutor executor = (ThreadPoolExecutor) eventLoopGroup;

            log.info("Netty Thread Pool Metrics:");
            log.info("Active Threads: {}", executor.getActiveCount());
            log.info("Pool Size: {}", executor.getPoolSize());
            log.info("Core Pool Size: {}", executor.getCorePoolSize());
            log.info("Maximum Pool Size: {}", executor.getMaximumPoolSize());
            log.info("Queue Size: {}", executor.getQueue().size());
            log.info("Completed Tasks: {}", executor.getCompletedTaskCount());
        }
    }
}
